//
//@File    :	12.11_queue.cpp
//@Time    :	2021/09/16 21:11:13
//@Auther  :	Sun Sheng
//@Contact :	970340843@qq.com
//@Desc    :	Queue and Customer methods
//

#include "12.10_queue.h"
#include <cstdlib>

//Queue methods
Queue::Queue(int qs):qsize(qs)
{
    front=rear=nullptr;//or NULL
    items=0;
}

Queue::~Queue()
{
    Node * temp;
    while (front != nullptr)//while queue is not yet empty
    {
        temp=front;//save address of front itrm
        front=front->next;//reset pointer to next item
        delete temp;//delete former front
    }
}

bool Queue::isempty() const
{
    return items==0;
}

bool Queue::isfull() const
{
    return items==qsize;
}

int Queue::queuecount() const 
{
    return items;
}

//Add item to queue
bool Queue::enqueue(const Item & item)
{
    if (isfull())
    {
        return false;
    }
    Node * add = new Node;//create node
    //on failure,new throws std::bad_alloc exception
    add->item=item;//set node pointers
    add->next=nullptr;//or NULL
    items++;
    if (front==nullptr)//if queue is empty
    {
        front=add;//place item at front
    }
    else
    {
        rear->next=add;//else place at rear
    }
    rear=add;          //have rear pointer to new node
    return true;
}

bool Queue::dequeue(Item & item)
{
    if (front==nullptr)
    {
        return false;
    }
    item=front->item;
    items--;
    Node * temp=front;
    front=front->next;
    delete temp;
    if (items==0)
    {
        rear=nullptr;
    }
    return true;
    
}

void Customer::set(long when)
{
    processtime = std::rand()%3+1;
    arrive = when;
}